package com.wontube.video.controller;

import java.util.Locale;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.wontube.client.extension.utils.StringUtils;
import com.wontube.client.modle.vo.PagenateInfo;
import com.wontube.client.remote.Remoting;
import com.wontube.smr.client.IShortFilmHandler;
import com.wontube.smr.client.model.vo.MovieItems;
import com.wontube.video.pub.AppConfig;
import com.wontube.video.pub.VideoCookieUtils;
import com.wontube.web.i18n.I18nMethod;

/**
 * @author LuoBiao
 * 
 */
@Controller
@RequestMapping(value = "/search")
public final class VideoController {	
	@RequestMapping(value = "")
	public ModelAndView search(HttpServletRequest request) {		
		return this.search("",request);
	}

	@RequestMapping(value = "/{query}")
	public ModelAndView search(@PathVariable("query") String query,HttpServletRequest request) {
		return this.search(query, 1,request);
	}

	/**
	 * 搜索视频
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/{query}/{page}")
	public ModelAndView search(@PathVariable("query") String query, @PathVariable("page") Integer page, HttpServletRequest request) {	
		String localeName = VideoCookieUtils.getLocaleName(request);
		if (StringUtils.isNullOrEmpty(localeName)) {
			localeName = "en_US";
		}
		

		ModelAndView mv = this.getI18nView(AppConfig.getLocale(localeName));
		mv.addObject("locale", localeName);
		mv.setViewName("video/search_video");
		
		Remoting<IShortFilmHandler> remoting = new Remoting<IShortFilmHandler>();
		IShortFilmHandler handler = remoting.createService(IShortFilmHandler.class);		

		PagenateInfo pageInfo = new PagenateInfo();
		pageInfo.setPageNo(page);
		pageInfo.setPageSize(10);
		MovieItems videoItems = handler.searchYouTube(query, pageInfo);

		if (!remoting.isDone()) {
			throw new RuntimeException(remoting.getLastErrMsg());
		}

		mv.addObject("videos", videoItems);
		mv.addObject("query", query);

		return mv;
	}

	private ModelAndView getI18nView(Locale locale){
		ModelAndView mv = new ModelAndView();
		mv.addObject("i18n", new I18nMethod(AppConfig.widgetBundleName, locale));
		return mv;
	}
}
